# -*- coding: utf-8 -*-

from django.http import HttpResponse
from django.template import loader
from django.template.response import TemplateResponse
from xadmin.views import BaseAdminPlugin
from xadmin.plugins.actions import BaseActionView

from .models import *


# 简单插件
class DemoPlugin(BaseAdminPlugin):

    demo_plugin = False

    def init_request(self, *args, **kwargs):
        # 是否实例化这个插件,当返回False时,不显示该插件
        return self.demo_plugin

    def block_top_toolbar(self, context, nodes):
        # 实例化插件
        if self.demo_plugin:

            content = 'Python + Django + xadmin 快速开发教程'
            # 更新模板内容
            context.update({
                'about_content': content
            })

            # 添加渲染后的节点
            nodes.append(
                loader.render_to_string('xadmin/blocks/model_list.top_toolbar.demo.html',
                                        context_instance=context)
            )


# 查询按钮
class QueryMenuPlugin(BaseAdminPlugin):

    demo_query_menu = False

    def init_request(self, *args, **kwargs):
        return self.demo_query_menu

    def block_top_toolbar(self, context, nodes):
        if self.demo_query_menu:
            nodes.append(
                loader.render_to_string('xadmin/blocks/model_list.top_toolbar.demo_query.html',
                                        context_instance=context)
            )


# 查询结果页面
class QueryView(BaseActionView):

    def do_action(self, context):
        return TemplateResponse(self.request,
                                self.get_template_list('views/demo_query.html'),
                                context, current_app=self.admin_site.name)


# 查询插件
class QueryPlugin(BaseAdminPlugin):

    def init_request(self, *args, **kwargs):
        # 根据POST请求，当demo_do参数是query时，才实例化
        return self.request.POST.get('demo_do') == 'query'

    # 生成页面
    def response_action(self, ac, context):
        if isinstance(ac, type) and issubclass(ac, BaseActionView):
            # 根据BaseActionView生成页面
            action_view = self.get_model_view(ac, self.admin_view.model)
            action_view.init_action(self.admin_view)
            return action_view.do_action(context)
        else:
            # 生成默认页面
            return ac(self.admin_view, self.request, context)

    def get_response(self, response, context, *args, **kwargs):
        names = self.request.POST.get('name')
        students = []
        if names is u'':
            students = Students.objects.all()
        else:
            names = (i.strip() for i in names.split('|'))
            students = Students.objects.filter(name__in=names)
        context.update({
            'students': students,
        })
        return self.response_action(QueryView, context)
